import type {
  PointsRecord,
  PointsApproval,
  PointsLedger,
  DepartmentPointsSummary,
  PointsQueryParams,
  CreatePointsRecordParams,
  ApprovePointsParams,
  BatchImportParams,
  PointsChartData,
  PointsTrendData,
  PointsRanking
} from '@/types/points'

// 模拟数据
const mockRecords: PointsRecord[] = [
  {
    id: '1',
    departmentId: '1',
    departmentName: '安全部',
    responsiblePersonId: 'u1',
    responsiblePersonName: '张三',
    eventDescription: '发现员工未佩戴安全帽进入施工现场',
    pointsType: 'deduct',
    pointsValue: 5,
    attachments: [],
    recorderId: 'u2',
    recorderName: '李四',
    recordTime: '2024-01-15 09:30:00',
    status: 'pending',
    location: 'A区施工现场',
    severity: 'medium'
  },
  {
    id: '2',
    departmentId: '2',
    departmentName: '生产部',
    responsiblePersonId: 'u3',
    responsiblePersonName: '王五',
    eventDescription: '主动发现并报告安全隐患，避免事故发生',
    pointsType: 'add',
    pointsValue: 10,
    attachments: [],
    recorderId: 'u4',
    recorderName: '赵六',
    recordTime: '2024-01-15 14:20:00',
    status: 'approved',
    location: 'B车间',
    severity: 'high'
  },
  {
    id: '3',
    departmentId: '1',
    departmentName: '安全部',
    responsiblePersonId: 'u5',
    responsiblePersonName: '孙七',
    eventDescription: '未按规定进行安全交底',
    pointsType: 'deduct',
    pointsValue: 3,
    attachments: [],
    recorderId: 'u6',
    recorderName: '周八',
    recordTime: '2024-01-14 16:45:00',
    status: 'approved',
    location: 'C区施工现场',
    severity: 'low'
  }
]

const mockApprovals: PointsApproval[] = [
  {
    id: '1',
    recordId: '1',
    record: mockRecords[0],
    approverId: 'u7',
    approverName: '吴九',
    approvalStatus: 'pending',
    createTime: '2024-01-15 09:35:00',
    updateTime: '2024-01-15 09:35:00'
  }
]

const mockLedgers: PointsLedger[] = [
  {
    id: '1',
    userId: 'u1',
    userName: '张三',
    departmentId: '1',
    departmentName: '安全部',
    totalPoints: 45,
    addPoints: 60,
    deductPoints: 15,
    recordCount: 12,
    lastUpdateTime: '2024-01-15 16:30:00'
  },
  {
    id: '2',
    userId: 'u3',
    userName: '王五',
    departmentId: '2',
    departmentName: '生产部',
    totalPoints: 38,
    addPoints: 50,
    deductPoints: 12,
    recordCount: 10,
    lastUpdateTime: '2024-01-15 15:20:00'
  }
]

const mockDepartmentSummary: DepartmentPointsSummary[] = [
  {
    departmentId: '1',
    departmentName: '安全部',
    totalPoints: 156,
    addPoints: 200,
    deductPoints: 44,
    averagePoints: 12.0,
    employeeCount: 13,
    ranking: 1,
    lastUpdateTime: '2024-01-15 16:30:00'
  },
  {
    departmentId: '2',
    departmentName: '生产部',
    totalPoints: 98,
    addPoints: 120,
    deductPoints: 22,
    averagePoints: 8.2,
    employeeCount: 12,
    ranking: 2,
    lastUpdateTime: '2024-01-15 15:20:00'
  }
]

// 模拟API延迟
const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms))

// 积分记录管理
export const pointsRecordApi = {
  // 获取积分记录列表
  getList: async (params: PointsQueryParams) => {
    await delay(500)
    
    let filteredRecords = [...mockRecords]
    
    // 应用筛选条件
    if (params.departmentId) {
      filteredRecords = filteredRecords.filter(record => record.departmentId === params.departmentId)
    }
    if (params.pointsType) {
      filteredRecords = filteredRecords.filter(record => record.pointsType === params.pointsType)
    }
    if (params.status) {
      filteredRecords = filteredRecords.filter(record => record.status === params.status)
    }
    if (params.keyword) {
      filteredRecords = filteredRecords.filter(record => 
        record.eventDescription.includes(params.keyword!) || 
        record.responsiblePersonName.includes(params.keyword!)
      )
    }
    
    const page = params.page || 1
    const pageSize = params.pageSize || 20
    const start = (page - 1) * pageSize
    const end = start + pageSize
    
    return {
      list: filteredRecords.slice(start, end),
      total: filteredRecords.length,
      page,
      pageSize
    }
  },

  // 获取积分记录详情
  getDetail: async (id: string) => {
    await delay(300)
    const record = mockRecords.find(r => r.id === id)
    if (!record) throw new Error('记录不存在')
    return record
  },

  // 创建积分记录
  create: async (data: CreatePointsRecordParams) => {
    await delay(800)
    const newRecord: PointsRecord = {
      id: Date.now().toString(),
      ...data,
      departmentName: data.departmentId === '1' ? '安全部' : '生产部',
      responsiblePersonName: '新用户',
      recorderId: 'current_user',
      recorderName: '当前用户',
      recordTime: new Date().toLocaleString(),
      status: 'pending',
      attachments: data.attachments || []
    }
    mockRecords.unshift(newRecord)
    return newRecord
  },

  // 更新积分记录
  update: async (id: string, data: Partial<CreatePointsRecordParams>) => {
    await delay(600)
    const index = mockRecords.findIndex(r => r.id === id)
    if (index === -1) throw new Error('记录不存在')
    
    mockRecords[index] = { ...mockRecords[index], ...data }
    return mockRecords[index]
  },

  // 删除积分记录
  delete: async (id: string) => {
    await delay(400)
    const index = mockRecords.findIndex(r => r.id === id)
    if (index === -1) throw new Error('记录不存在')
    mockRecords.splice(index, 1)
  },

  // 批量导入积分记录
  batchImport: async (data: BatchImportParams) => {
    await delay(2000)
    return {
      successCount: 5,
      failCount: 1,
      errors: ['第3行数据格式错误']
    }
  },

  // 下载导入模板
  downloadTemplate: async () => {
    await delay(500)
    // 返回模拟的Excel文件
    return new Blob(['模拟Excel内容'], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
  }
}

// 积分审批管理
export const pointsApprovalApi = {
  // 获取待审批列表
  getPendingList: async (params: PointsQueryParams) => {
    await delay(500)
    return {
      list: mockApprovals,
      total: mockApprovals.length,
      page: params.page || 1,
      pageSize: params.pageSize || 20
    }
  },

  // 获取我的审批列表
  getMyApprovals: async (params: PointsQueryParams) => {
    await delay(500)
    return {
      list: mockApprovals,
      total: mockApprovals.length,
      page: params.page || 1,
      pageSize: params.pageSize || 20
    }
  },

  // 获取审批详情
  getDetail: async (id: string) => {
    await delay(300)
    const approval = mockApprovals.find(a => a.id === id)
    if (!approval) throw new Error('审批记录不存在')
    return approval
  },

  // 审批积分记录
  approve: async (data: ApprovePointsParams) => {
    await delay(1000)
    const approval = mockApprovals.find(a => a.id === data.approvalId)
    if (!approval) throw new Error('审批记录不存在')
    
    approval.approvalStatus = data.approvalStatus
    approval.approvalTime = new Date().toLocaleString()
    approval.approvalComment = data.approvalComment
    
    // 更新对应记录的状态
    const record = mockRecords.find(r => r.id === approval.recordId)
    if (record) {
      record.status = data.approvalStatus === 'approved' ? 'approved' : 'rejected'
      record.approvalTime = approval.approvalTime
      record.approvalComment = data.approvalComment
    }
    
    return approval
  },

  // 获取审批历史
  getHistory: async (recordId: string) => {
    await delay(300)
    return mockApprovals.filter(a => a.recordId === recordId)
  }
}

// 积分台账管理
export const pointsLedgerApi = {
  // 获取个人积分台账
  getPersonalLedger: async (userId: string, params: PointsQueryParams) => {
    await delay(500)
    const ledger = mockLedgers.find(l => l.userId === userId)
    const records = mockRecords.filter(r => r.responsiblePersonId === userId)
    
    return {
      ledger: ledger || mockLedgers[0],
      records,
      total: records.length
    }
  },

  // 获取部门积分汇总
  getDepartmentSummary: async (params: PointsQueryParams) => {
    await delay(500)
    return {
      list: mockDepartmentSummary,
      total: mockDepartmentSummary.length
    }
  },

  // 获取积分排行榜
  getRanking: async (params: {
    type: 'personal' | 'department'
    timeRange?: string
    limit?: number
  }) => {
    await delay(500)
    const rankings: PointsRanking[] = mockLedgers.map((ledger, index) => ({
      rank: index + 1,
      userId: ledger.userId,
      userName: ledger.userName,
      departmentName: ledger.departmentName,
      totalPoints: ledger.totalPoints,
      addPoints: ledger.addPoints,
      deductPoints: ledger.deductPoints
    }))
    
    return rankings.slice(0, params.limit || 10)
  }
}

// 积分统计分析
export const pointsStatisticsApi = {
  // 获取积分趋势数据
  getTrendData: async (params: {
    timeRange: string
    type: 'daily' | 'weekly' | 'monthly'
    departmentId?: string
  }) => {
    await delay(500)
    const trendData: PointsTrendData[] = [
      { date: '2024-01-10', addPoints: 20, deductPoints: 5, netPoints: 15 },
      { date: '2024-01-11', addPoints: 15, deductPoints: 8, netPoints: 7 },
      { date: '2024-01-12', addPoints: 25, deductPoints: 3, netPoints: 22 },
      { date: '2024-01-13', addPoints: 18, deductPoints: 12, netPoints: 6 },
      { date: '2024-01-14', addPoints: 22, deductPoints: 7, netPoints: 15 },
      { date: '2024-01-15', addPoints: 30, deductPoints: 10, netPoints: 20 }
    ]
    return trendData
  },

  // 获取积分分布图表数据
  getDistributionChart: async (params: {
    type: 'department' | 'points-type'
    timeRange?: string
  }) => {
    await delay(500)
    const chartData: PointsChartData = {
      labels: ['安全部', '生产部', '技术部', '质量部'],
      datasets: [{
        label: '积分分布',
        data: [156, 98, 76, 45],
        backgroundColor: ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C']
      }]
    }
    return chartData
  },

  // 获取积分统计概览
  getOverview: async (params: {
    timeRange?: string
    departmentId?: string
  }) => {
    await delay(500)
    return {
      totalRecords: 156,
      totalAddPoints: 1250,
      totalDeductPoints: 680,
      netPoints: 570,
      pendingApprovals: 8,
      averagePoints: 3.7,
      topDepartment: '安全部'
    }
  },

  // 导出积分报表
  exportReport: async (params: {
    type: 'personal' | 'department' | 'all'
    format: 'excel' | 'pdf'
    timeRange?: string
    departmentId?: string
  }) => {
    await delay(2000)
    // 返回模拟的导出文件
    const content = params.format === 'excel' ? '模拟Excel内容' : '模拟PDF内容'
    return new Blob([content], { 
      type: params.format === 'excel' 
        ? 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        : 'application/pdf'
    })
  }
}